// distribution/index/index.js
const api = require("../../request/api");
const request = require("../../request/request");
const util = require("../../utils/util");
const App = getApp();
const defaultAvatarUrl =
    "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0";

Page({
    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,
        styledata: {
            bg_color: "white",
            color: "#000",
            leftflag: true,
            // "homeflag": true,
            name: "分销中心",
        },

        // 可提现金额
        availableMoney: "0.00",

        tip: "展示更多 ∨",
        isShow: true,

        uid: "",
        nickname: "游客",
        avatarUrl: defaultAvatarUrl,
        mobile: "",
        userInfo: {},
        options: {},

        good_info: {},

        today_order_num: 0,
        total_order_num: 0,
        today_consumer_num: 0,
        total_consumer_num: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        this.init_data(options);

        await this.getInfomation();
        await this.getShareGood();
        await this.updateCountData();
    },

    init_data(options) {
        this.setData({
            uid: App.globalData.uid,
            userInfo: App.globalData.userInfo,
            avatarUrl: App.globalData?.fulluserInfo?.avatar || defaultAvatarUrl,
            nickname: App.globalData?.fulluserInfo?.name || "游客",
            mobile: App.globalData.mobile,
            options,
        });
    },

    // 点击显示或隐藏详情盒子
    toggleShow() {
        this.setData({
            tip: this.data.isShow ? "展示更多 ∨" : "∧",
            isShow: !this.data.isShow,
        });
    },

    // 跳转提现页面
    gotocash() {
        wx.navigateTo({
            url: "/pages/cash/cash",
            success: (result) => { },
            fail: () => { },
            complete: () => { },
        });
    },

    // 跳转分销商品页面
    showMoreGoods() {
        let url = "/distribution/goodlist/goodlist";

        wx.navigateTo({
            url: url,
            success: (result) => { },
            fail: () => { },
            complete: () => { },
        });
    },

    // 获取爆款分销商品
    async getShareGood() {
        let params = {
            page: this.page,
            limit: 1,
            // type: this.data.type,
            brand_id: 2,
        };

        let res = await request.post(api.goods_list, params);

        // 计算最高可赚佣金
        res.forEach((item) => {
            item.highestCommision = (item.sell_price * 0.1).toFixed(2);
        });

        console.log(res);
        this.setData({
            good_info: res[0],
        });
    },

    // 获取分销数据（收益数值等）
    async getInfomation() {
        let info = await request.post(api.myinfo, { uid: this.data.uid });

        this.setData({
            myinfo: info,
        });
        console.log(info);
    },

    // 跳转分销订单
    gotoOrders(e) {
        let type = e.currentTarget.dataset.type;
        wx.navigateTo({
            url: `/distribution/order/order?type=${type}`,
            success: (result) => { },
            fail: () => { },
            complete: () => { },
        });
    },

    // 跳转分销客户
    gotoConsumer(e) {
        let type = e.currentTarget.dataset.type;
        wx.navigateTo({
            url: `/distribution/consumer/consumer?type=${type}`,
            success: (result) => { },
            fail: () => { },
            complete: () => { },
        });
    },

    // 更新分账订单、邀请客户的数量
    async updateCountData() {
        // 两个接口传参一致 可以复用
        let params1 = {
            user_id: this.data.uid,
            type: 1,
            page: 1,
            limit: 1,
        };
        let params2 = {
            user_id: this.data.uid,
            type: 0,
            page: 1,
            limit: 1,
        };

        // let today_order = await request.postall(api.orderAgentlogList, params1)
        // let total_order = await request.postall(api.orderAgentlogList, params2)
        let today_consumer = await request.postall(api.queryMymember, params1);
        let total_consumer = await request.postall(api.queryMymember, params2);

        this.setData({
            // today_order_num: today_order.count,
            // total_order_num: total_order.count,
            today_consumer_num: today_consumer.count,
            total_consumer_num: total_consumer.count,
        });
    },

    gotoShareSort() {
        wx.navigateTo({
            url: "/distribution/sharesort/sharesort",
            success: (result) => { },
            fail: (err) => {
                console.log(err);
            },
            complete: () => { },
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() { },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() { },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() { },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() { },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() { },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() { },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(e) {
        let mobile = App.globalData.mobile;
        let VipGrade = this.data.VipGrade;
        let uid = this.data.uid;
        let id = e.target.dataset.id;
        let title = e.target.dataset.title;
        let imgurl = e.target.dataset.imgurl;

        let sid = `${uid}a${id}a1`;

        // 记录分享次数
        request
            .postall(api.wxacodeshare, { uid: this.data.uid, sid: sid })
            .then((res) => {
                console.log(res);
            });

        let nobind = 1; // 正常不绑定关系
        if (mobile.length == 11 && VipGrade >= 1) {
            nobind = 0; // 如果是分销员 则置零 绑定关系
        }

        let share_path = `/pages/good/detail`;
        let sharePath = `/pages/home/home?share=${share_path}&sid=${sid}&id=${this.data.goods_id}&nobind=${nobind}`;

        // 底下邀请好友 无商品ID时执行调用
        if (!id) {
            sid = this.data.uid;
            nobind = 0;
            sharePath = `/pages/home/home?sid=${sid}&nobind=${nobind}`;
        }

        let shareObj = {
            title: title,
            path: sharePath,
            imageUrl: imgurl,
            success: function (res) {
                if (res.errMsg == "shareAppMessage:ok") {
                    util.showToast("分享成功");
                }
            },
            fail: function (err) {
                console.log(err);
                util.showToast("分享失败");
            },
        };
        console.log("shareObj", shareObj);

        return shareObj;
    },
});
